import React from 'react'
import { LoginOutlined } from '@ant-design/icons'
import { Input, Button, message, Popover, Form } from 'antd'
import { SERVER_ADMIN } from 'configs/service'
import axios from 'axios'
import { checkres, session } from 'utils'

export default function Login() {
  const uuid = React.useRef(Math.random())
  const [visible, setVisible] = React.useState(false)
  const [captcha, setCaptcha] = React.useState()
  const [form] = Form.useForm()

  React.useEffect(() => {
    if (visible) updateCaptcha()
  }, [visible])

  function updateCaptcha() {
    setCaptcha(
      `${SERVER_ADMIN}/sys/captchaJpg?uuid=${uuid.current}&date=${Date.now()}`
    )
  }

  function onSubmit() {
    form.validateFields().then(values => {
      values.password = window.btoa(values.password)
      axios
        .post(
          '/sys/login',
          { ...values, uuid: uuid.current },
          { baseURL: SERVER_ADMIN }
        )
        .then(res => {
          if (!checkres(res)) {
            updateCaptcha()
            return
          }
          const { token, user } = res.data.data
          session.Authorization = token
          session.userData = user
          axios.defaults.headers.common.Authorization = token
          message.success('登录成功')
          setVisible(false)
        })
    })
  }

  return (
    <Popover
      title={
        session.userData
          ? '已登录，当前用户：' + session.userData?.username
          : '未登录'
      }
      trigger="click"
      visible={visible}
      onVisibleChange={v => setVisible(v)}
      content={
        <Form
          form={form}
          onFinish={onSubmit}
          layout="vertical"
          style={{ width: 240 }}
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input
              type="text"
              autoComplete="username"
              placeholder="用户名"
            ></Input>
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input
              type="password"
              placeholder="密码"
              autoComplete="current-password"
            ></Input>
          </Form.Item>
          <div style={{ display: 'flex' }}>
            <Form.Item
              name="captcha"
              rules={[{ required: true, message: '请输入验证码' }]}
            >
              <Input type="text" placeholder="验证码"></Input>
            </Form.Item>
            <img
              src={captcha}
              height={32}
              onClick={() => updateCaptcha()}
              style={{ marginLeft: 6 }}
            ></img>
          </div>
          <Button type="primary" htmlType="submit" style={{ width: '100%' }}>
            登录
          </Button>
        </Form>
      }
      placement="topRight"
    >
      <Button
        type="primary"
        size="large"
        shape="circle"
        icon={<LoginOutlined />}
        style={{ position: 'fixed', bottom: 24, right: 74, zIndex: 999 }}
      ></Button>
    </Popover>
  )
}
